let currentElement = null;
let currentHighlight = null;
let isSelecting = false;
let originalStyles = new Map();
let realTarget = null;
let elementInfo = null;

// 创建高亮元素
function createHighlight(element) {
  if (currentElement === element) return;
  if (currentHighlight) {
    currentHighlight.remove();
  }

  // 恢复之前元素的样式
  if (currentElement) {
    restoreElementStyle(currentElement);
  }

  // 获取目标元素的位置信息
  const rect = element.getBoundingClientRect();
  // 获取水平滚动位置（横轴）
  const scrollLeft = window.scrollX || document.documentElement.scrollLeft;
  // 获取垂直滚动位置（纵轴）
  const scrollTop = window.scrollY || document.documentElement.scrollTop;

  // 创建高亮div
  currentHighlight = document.createElement('div');
  Object.assign(currentHighlight.style, {
    position: 'absolute',
    top: (rect.top + scrollTop) + 'px',
    left: (rect.left + scrollLeft) + 'px',
    width: rect.width + 'px',
    height: rect.height + 'px',
    boxSizing: 'border-box',
    border: '2px solid #f56c6c',
    backgroundColor: 'rgba(245, 108, 108, 0.2)',
    pointerEvents: 'none',
    zIndex: 9999,
    transition: 'all 0.3s ease-out'
  });
  document.body.appendChild(currentHighlight);

  currentElement = element;
}

// 恢复元素样式
function restoreElementStyle(element) {
  if (currentHighlight) {
    currentHighlight.remove();
    currentHighlight = null;
  }
}

// 获取元素信息
function getElementInfo(element) {
  const info = {
    tagName: element.tagName,
    id: element.id || '无',
    class: element.className || '无',
    innerText: element.innerText.substring(0, 50) + (element.innerText.length > 50 ? '...' : ''),
    attributes: {},
    xpath: getXPath(element)
  };

  // 获取元素属性
  Array.from(element.attributes).forEach(attr => {
    info.attributes[attr.name] = attr.value;
  });

  return info;
}

function findDocument(_node, e) {  
  // 解决Dom嵌套Dom，导致无法获取正常节点的bug
  let realTarget = document.elementFromPoint(e.clientX, e.clientY);
  let limit = 6;
  let deep = 0; // 限制Dom嵌套查找深度
  function func(node) {  
    // console.log("node", node, node.shadowRoot);
    if (node.shadowRoot) {
      let shadowRoot = node.shadowRoot;
      let target = shadowRoot.elementFromPoint(e.clientX, e.clientY);
      // console.log("target", target);
      if (target) {
        realTarget = target
        deep++;
        if (deep >= limit) return;
        func(target)
      } else {
        return;
      }
    } else {
      // 递归处理当前元素的子节点
      if (deep >= limit) return;
      const children = node.children;
      for (let i = 0; i < children.length; i++) {
        func(children[i]);
      }
    }
  }

  func(_node);
  return realTarget;
}

// 鼠标移动事件处理
let mouseMoveHandler = null;
function handleMouseMove() {
  // 制作函数防抖
  let timeout = null;
  return (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      timeout = null;
      realTarget = findDocument(document, e)
      // 高亮当前元素
      realTarget && createHighlight(realTarget);
    }, 50);
  }
}

// 点击事件处理
function handleClick(e) {
  if (!isSelecting) return;

  e.stopPropagation();
  e.preventDefault();

  elementInfo = getElementInfo(currentElement);
  console.log("elementInfo", elementInfo);

  // 发送元素信息到popup
  chrome.runtime.sendMessage({
    action: 'elementSelected',
    data: elementInfo
  });

  // 停止选择模式
  stopSelection();
}

// copy 代码到剪贴板
function copyToClipboard() {
  // 复制 xpath 到剪贴板
  if (elementInfo.xpath) {
    navigator.clipboard.writeText(elementInfo.xpath).then(() => {
      showToast('元素 XPath 已复制！');
    }).catch(() => {
      showToast('复制 XPath 失败，请手动复制');
    });
  }
}

// 显示提示信息
function showToast(message) {
  // 防止多次弹出
  if (document.getElementById('my-chrome-ext-toast')) return;

  const toast = document.createElement('div');
  toast.id = 'my-chrome-ext-toast';
  toast.innerText = message;
  Object.assign(toast.style, {
    position: 'fixed',
    top: '20px',
    left: '50%',
    transform: 'translateX(-50%)',
    background: 'rgba(60,60,60,0.95)',
    color: '#fff',
    padding: '10px 24px',
    borderRadius: '6px',
    fontSize: '16px',
    zIndex: 99999,
    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
    transition: 'opacity 0.3s',
    opacity: 1,
  });
  document.body.appendChild(toast);

  setTimeout(() => {
    toast.style.opacity = 0;
    setTimeout(() => {
      toast.remove();
    }, 300);
  }, 1500);
}

// 开始选择元素
function startSelection() {
  if (isSelecting) return; // 如果已经在选择模式中，则不重复开始
  isSelecting = true;
  // 清除之前的选择状态
  realTarget = null;
  elementInfo = null;
  mouseMoveHandler = handleMouseMove();
  document.addEventListener('mousemove', mouseMoveHandler);
  document.addEventListener('click', handleClick, true);
}

// 停止选择元素
function stopSelection() {
  isSelecting = false;
  document.removeEventListener('mousemove', mouseMoveHandler);
  document.removeEventListener('click', handleClick, true);
  // 恢复之前元素的样式
  if (currentElement) {
    restoreElementStyle(currentElement);
  }
}

// 消息监听
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'startSelection') {
    if (!isSelecting) {
      startSelection();
    } else {
      stopSelection();
    }
  } else if (message.action === 'stopSelection') {
    stopSelection();
  } else if (message.action === 'copyElement') { 
    copyToClipboard();
  }
  return true; // 保持消息通道打开，以便异步发送响应
});